﻿using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace CodeMan.EntityFrameworkCore
{
    /* This class is needed for EF Core console commands
     * (like Add-Migration and Update-Database commands) */
    public class CodeManMigrationsDbContextFactory : IDesignTimeDbContextFactory<CodeManMigrationsDbContext>
    {

        public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
        {
            builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
        });
        public CodeManMigrationsDbContext CreateDbContext(string[] args)
        {
            CodeManEfCoreEntityExtensionMappings.Configure();

            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<CodeManMigrationsDbContext>()
                .UseSqlServer(configuration.GetConnectionString("DefaultMMSql"))
                //.UseSqlite(configuration.GetConnectionString("DefaultSqlite"))
                .UseLoggerFactory(efLogger);

            return new CodeManMigrationsDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../CodeMan.DbMigrator/"))
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}
